// localLifePackage/pages/orderPay/orderPay.js
var common = require("../../../common/common.js").common;

var QQMapWX = require("../../../sdk/qqmap-wx-jssdk.min.js");

var util = require("../../../utils/util.js");

const app = getApp();

Page({
    /**
   * 页面的初始数据
   */
    data: {
        // position:['',''],
        payment_channel: 2,
        expressPro: [],
        chose_delivery_channel: 1,
        chose_delivery_channel_name: "",
        discount_alert: 0,
        delivery_time_switch: 0,
        discount_label: 1,
        remark: "",
        componentStyle: {
            navigationTitle: "立即支付",
            goBack: 2
        },
        payWayList: [],
        payWayList1: [ {
            iconfonts: "icon-yue",
            //支付方式icon
            payWayName: "余额",
            //支付方式名称pay
            id: 1,
            color: "#FFAE00",
            //icon颜色,
            isDisabled: false,
            //是否禁用
            isShow: true
        }, {
            iconfonts: "icon-weixinzhifu",
            payWayName: "微信支付",
            id: 2,
            color: "#45C144",
            isDisabled: false,
            isShow: true
        } ],
        voucher_use: true,
        voucher_id: "",
        isPayStatus: true,
        multiIndex: [ 0, 0 ],
        rider_time_range_new: [],
        delivery_time: ""
    },
    //获取去右侧胶囊的信息
    getHeader() {
        let menuRect = wx.getMenuButtonBoundingClientRect();
        this.setData({
            topBarHeight: menuRect.height,
            topBarTop: menuRect.top
        });
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        this.getHeader();
        let _this = this;
        var sku_item = options.sku_item.split("|");
        var items = [];
        sku_item.forEach((item, index) => {
            var item = item.split(",");
            items.push({
                sku_id: item[0],
                num: item[1]
            });
        });
        if (options.is_single == "undefined") {
            options.is_single = "";
        }
        _this.setData({
            items: items,
            business_id: options.id,
            domain: app.globalData.domain.slice(0, -10),
            currentOptions: options
        });
        var p1 = _this.getRecieverInfo();
        var p2 = _this.getBase();
        const system = wx.getSystemInfoSync().system;
        const isIOS = system.includes("iOS");
        this.setData({
            isIOS: isIOS
        });
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {
        this.getRecieverInfo();
        this.getInitDate("init");
    },
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {},
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {},
    /**
   * 用户点击右上角分享
   */
    onShareAppMessage: function() {},
    //全局基础配置信息
    getBase: function() {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            method: "get",
            data: {},
            success: res => {
                wx.setNavigationBarTitle({
                    title: res.extra.title
                });
                wx.setNavigationBarColor({
                    frontColor: "#ffffff",
                    backgroundColor: res.extra.color_main
                });
                that.setData({
                    color_main: res.extra.color_main,
                    color_minor: res.extra.color_minor,
                    apptitle: res.extra.title,
                    style: res.extra.style,
                    leader_change: res.extra.l_change,
                    rp_name: res.extra.rp_name,
                    order_start: res.extra.order_start,
                    order_start_switch: res.extra.order_start_switch,
                    leaderName: res.extra.leader_title ? res.extra.leader_title : "团长",
                    ["goodsListStyle.leaderName"]: res.extra.leader_title ? res.extra.leader_title : "团长",
                    communityName: res.extra.community_title ? res.extra.community_title : "社区",
                    leader_address_on: res.extra.leader_address_on,
                    integral_status: res.extra.integral_status
                });
                //处理模块开关
                                var features = common.getModulesSwich(res.extra.features);
                //处理数据格式
                                that.setData({
                    features: features
                });
                //设置模块颜色
                                var componentStyle = that.data.componentStyle;
                that.setData({
                    componentStyle: {
                        ...componentStyle,
                        color_main: !res.extra.color_main ? "#FE513B" : res.extra.color_main,
                        color_minor: !res.extra.color_minor ? "#FE513B" : res.extra.color_minor
                    }
                });
            }
        });
    },
    // 获取当前日期之后或之前的七天
    getInitDate(type) {
        var date = new Date();
        var base = new Date(date).getTime();
        var oneDay = 24 * 3600 * 1e3;
        var date = [];
        var data = [ Math.random() * 300 ];
        var time = new Date(base);
        date.push([ time.getFullYear(), time.getMonth() + 1 < 10 ? "0" + (time.getMonth() + 1) : time.getMonth() + 1, time.getDate() < 10 ? "0" + time.getDate() : time.getDate() ].join("-"));
        for (var i = 1; i < 7; i++) {
            //控制需要的天数
            var now = new Date(base += oneDay);
            date.push([ now.getFullYear(), now.getMonth() + 1 < 10 ? "0" + (now.getMonth() + 1) : now.getMonth() + 1, now.getDate() < 10 ? "0" + now.getDate() : now.getDate() ].join("-"));
            data.push(Math.round((Math.random() - .5) * 20 + data[i - 1]));
        }
        let rime_arr = [];
        if (type == "init") {
            //  从当前时间开始显示可约 （分钟不是整点只能从下一个小时约）
            console.log(time.getMinutes());
            let hour = time.getMinutes() != 0 ? time.getHours() + 1 : time.getHours();
            console.log(hour);
            if (hour <= 23) {
                rime_arr = this.getTimeRange(hour);
            } else {
                date.splice(0, 1);
                rime_arr = this.getTimeRange(0);
            }
        } else {
            //从00:00 开始每一小时间隔显示
            rime_arr = this.getTimeRange(0);
        }
        let arrs = [ date, rime_arr ];
        this.setData({
            rider_time_range_new: arrs
        });
    },
    getTimeRange: function(start_time) {
        let hour = "";
        let rime_arr = [];
        for (var i = start_time; i < 24; i++) {
            hour = `${i < 10 ? "0" + i : i}:00 ~ ${i + 1 < 10 ? "0" + (i + 1) : i + 1 == 24 ? "00" : i + 1}:00`;
            rime_arr.push(hour);
        }
        return rime_arr;
    },
    bindColumnChangeRider: function(e) {
        console.log(e.detail);
        let column = e.detail.column;
        let value = e.detail.value;
        if (column == 0) {
            //监测第一列的变化
            this.getInitDate(`${value == 0 ? "init" : 0}`);
        }
    },
    bindMultiPickerChange: function(e) {
        let index = e.detail.value;
        let delivery_time = `${this.data.rider_time_range_new[0][index[0]]} ${this.data.rider_time_range_new[1][index[1]]}`;
        this.setData({
            multiIndex: e.detail.value,
            delivery_time: delivery_time
        });
    },
    getRecieverInfo() {
        let that = this;
        var reciever = app.globalData.reciever;
        if (reciever) {
            that.setData({
                recieverInfo: {
                    ...reciever,
                    url: "/addressManagerPackage/pages/addressList/addressList"
                }
            });
            that.getOrder();
        } else {
            common.request({
                endpoint: "member/def_address",
                method: "post",
                data: {},
                success(res) {
                    var data = res.extra;
                    if (data) {
                        var recieverInfo = {
                            receiverName: data.name,
                            //收货人名称
                            phone: data.phone,
                            //电话
                            address: data.city + " " + data.area,
                            //收货地址
                            city: data.city,
                            area: data.area,
                            position: data.position,
                            lng: data.position ? data.position.split(",")[0] : "",
                            lat: data.position ? data.position.split(",")[1] : "",
                            url: "/addressManagerPackage/pages/addressList/addressList",
                            //跳转地址管理页面路径
                            wwb_street_id: data.wwb_street_id
                        };
                        app.globalData.reciever = recieverInfo;
                        that.setData({
                            recieverInfo: recieverInfo
                        });
                        that.getOrder();
                    } else {
                        var recieverInfo = {
                            url: "/addressManagerPackage/pages/addressList/addressList"
                        };
                        that.setData({
                            recieverInfo: recieverInfo
                        });
                        that.getOrder();
                    }
                },
                fail(err) {}
            });
        }
    },
    //预下单
    getOrder: function() {
        let _this = this;
        var {items: items, business_id: business_id, chose_delivery_channel: chose_delivery_channel, voucher_use: voucher_use, voucher_id: voucher_id, recieverInfo: recieverInfo} = _this.data;
        var params = {
            items: items,
            business_id: business_id,
            chose_delivery_channel: chose_delivery_channel,
            voucher_id: voucher_id,
            voucher_use: voucher_use,
            // position
            position: _this.data.recieverInfo.position,
            receiver_name: _this.data.recieverInfo.receiverName,
            receiver_phone: _this.data.recieverInfo.phone,
            address_detail: _this.data.recieverInfo.address,
            receiver_phone: _this.data.recieverInfo.phone,
            //此处增加 solit_id参数
            solit_id: _this.data.currentOptions.solit_id
        };
        return new Promise((resolve, reject) => {
            common.request({
                endpoint: "v1/Supermarket/order/create-pre-order",
                method: "post",
                data: params,
                success: res => {
                    var details = res.extra;
                    //设置红包
                                        _this.setVoucher(details);
                    //支付方式
                                        _this.setPayWay(details);
                    let chose_delivery_channel_default = 1;
                    let chose_delivery_channel_name = "";
                    details.delivery_types.forEach((i, j) => {
                        if (i.is_chose) {
                            chose_delivery_channel_default = i.channel;
                            chose_delivery_channel_name = i.name;
                        }
                    });
                    _this.setData({
                        business_info: details.business_info,
                        delivery_types: details.delivery_types,
                        //配送方式
                        chose_delivery_channel: chose_delivery_channel_default,
                        //默认配送方式
                        products: details.products,
                        //商品
                        voucher: details.voucher,
                        //红包
                        voucher_id: details.voucher.use_voucher_id,
                        delivery_fee_info: details.delivery_fee_info,
                        //配送费
                        full_discount: res.extra.full_discount,
                        //满减
                        total_amount: res.extra.total_amount,
                        //实付金额
                        total_amount_origin: res.extra.total_amount_origin,
                        //原价
                        total_discount: res.extra.total_discount,
                        //优惠金额
                        chose_delivery_channel_name: chose_delivery_channel_name,
                        delivery_time_switch: res.extra.delivery_time_switch
                    });
                    resolve();
                },
                fail(res) {
                    if (res.code == 1007) {
                        wx.showModal({
                            title: "提示",
                            content: "地址未获取到经纬度坐标，请重新获取",
                            complete: function(res) {
                                wx.navigateTo({
                                    url: "/addressManagerPackage/pages/addressList/addressList"
                                });
                            }
                        });
                        return;
                    }
                    wx.showModal({
                        title: "提示",
                        content: res.message,
                        complete: function(res) {
                            setTimeout(() => {
                                wx.navigateBack({
                                    delta: 0
                                });
                            }, 2e3);
                            resolve();
                        }
                    });
                }
            });
        });
    },
    //设置已红包
    setVoucher: function(detail) {
        var _this = this;
        if (!detail.voucher.voucher_info) {
            return false;
        }
        var usable = detail.voucher.voucher_info.usable;
        if (detail.voucher.voucher_display == 1 && detail.voucher.use_voucher_id) {
            usable.forEach(item => {
                if (item.id == detail.voucher.use_voucher_id) {
                    _this.setData({
                        voucher_use_item: item
                    });
                }
            });
        }
    },
    //选择支付方式
    radioChange: function(e) {
        this.setData({
            payment_channel: e.detail.value
        });
    },
    confirmInfo: function() {
        let that = this;
        if (!that.data.recieverInfo.area && that.data.chose_delivery_channel != 1 || !that.data.recieverInfo.area && that.data.expressPro.length) {
            //除快递和自提不用地址
            wx.showModal({
                title: "提示",
                content: "暂无地址信息,请先选择地址！",
                success(res) {
                    if (res.confirm) {
                        wx.navigateTo({
                            url: "/addressManagerPackage/pages/addressList/addressList"
                        });
                    }
                }
            });
            return false;
        }
        if (that.data.chose_delivery_channel == 2 && that.data.delivery_time_switch == 1 && !that.data.delivery_time) {
            wx.showModal({
                title: "提示",
                content: "请选择预约时间！",
                success(res) {
                    if (res.confirm) {}
                }
            });
            return false;
        }
        // var payButtonDisabled = that.data.payButtonDisabled;
        // if (!this.data.isPayStatus || payButtonDisabled) {
        //   //不满足满减条件或按钮禁用
        //   return false;
        // }
        // that.setData({
        //   payButtonDisabled: true //禁用支付按钮
        // })
        // 验证收件人信息
                var recieverInfo = that.data.recieverInfo;
        if (!recieverInfo.receiverName) {
            wx.showModal({
                title: "提示",
                content: "请选择收件人",
                showCancel: false,
                success(res) {
                    if (res.confirm) {
                        that.setData({
                            payButtonDisabled: false
                        });
                    }
                }
            });
            return false;
        }
        if (!/^1[23456789]\d{9}$/.test(recieverInfo.phone) && that.data.chose_delivery_channel == 1) {
            wx.showModal({
                title: "提示",
                content: "请输入正确的手机号码！",
                showCancel: false,
                success(res) {
                    if (res.confirm) {
                        that.setData({
                            payButtonDisabled: false
                        });
                    }
                }
            });
            return false;
        }
        var payment_channel = that.data.payment_channel;
        // console.log('payment_channel=' + payment_channel);
                if (payment_channel == 1) {
            //余额
            that.setData({
                confirm_lead: 0,
                payName: "余额",
                balance_confirm: 1
            });
        } else if (payment_channel == 2) {
            //微信支付
            that.confirm_order();
        }
    },
    confirm_order: common.throttle(function() {
        var _this = this;
        wx.showLoading({
            title: "订单支付中..."
        });
        var {items: items, business_id: business_id, chose_delivery_channel: chose_delivery_channel, payment_channel: payment_channel, position: position, voucher_use: voucher_use, voucher_id: voucher_id, recieverInfo: recieverInfo} = _this.data;
        var params = {
            items: items,
            business_id: business_id,
            chose_delivery_channel: chose_delivery_channel,
            payment_channel: payment_channel,
            position: recieverInfo.position,
            voucher_use: voucher_use,
            voucher_id: voucher_id,
            address_name: recieverInfo.city,
            address_detail: recieverInfo.area,
            receiver_name: recieverInfo.receiverName,
            receiver_phone: recieverInfo.phone,
            remark: _this.data.remark,
            //此处增加 solit_id参数
            solit_id: _this.data.currentOptions.solit_id
        };
        // console.log(params);
        // return;
                common.request({
            endpoint: "v1/Supermarket/order/create-order",
            method: "post",
            data: params,
            success: res => {
                wx.hideLoading();
                if (_this.data.currentOptions.solit_id) {
                    //接龙下单后清空缓存
                    // wx.removeStorageSync(`dragon_cart_${_this.data.currentOptions.solit_id}`)
                    // wx.removeStorageSync(`dragon_cart_count_${_this.data.currentOptions.solit_id}`)
                    //2023.5.18 修改群接龙 - 订单生成后，删除购物车中已生成订单的商品
                    let cart = wx.getStorageSync(`dragon_cart_${_this.data.currentOptions.solit_id}`);
                    let cartList = cart.filter(item => !_this.data.items.some(ele => ele.sku_id == item.id));
                    let cart_count = 0;
                    cartList.map(x => {
                        cart_count += x.count;
                    });
                    wx.setStorageSync(`dragon_cart_${_this.data.currentOptions.solit_id}`, cartList);
                    wx.setStorageSync(`dragon_cart_count_${_this.data.currentOptions.solit_id}`, cart_count);
                }
                if (payment_channel == 2) {
                    _this.payWay(res.extra);
                } else {
                    _this.setData({
                        balance_confirm: 0
                    });
                    common.request({
                        endpoint: "v1/Supermarket/order/sync-notify",
                        method: "post",
                        data: {
                            order_sn: res.extra.trade_no
                        },
                        success: res => {
                            setTimeout(function() {
                                wx.reLaunch({
                                    url: "/localLifePackage/pages/order/order"
                                });
                            }, 500);
                        },
                        fail(err) {
                            wx.showModal({
                                title: "提示",
                                content: err.message
                            });
                        }
                    });
                }
            },
            fail(err) {
                wx.hideLoading();
                wx.showModal({
                    title: "提示",
                    content: err.message
                });
            }
        });
    }, 3e3),
    payWay(res) {
        let that = this;
        let payment_channel = that.data.payment_channel;
        var order_no = res.trade_no;
        if (payment_channel == 2) {
            //微信支付
            wx.requestPayment({
                timeStamp: res.pay.timeStamp,
                nonceStr: res.pay.nonceStr,
                package: res.pay.package,
                signType: res.pay.signType,
                paySign: res.pay.paySign,
                success: function(res) {
                    // console.log(res);
                    wx.showToast({
                        title: "支付成功",
                        icon: "success",
                        mask: true,
                        duration: 3e3,
                        success: function(res) {
                            wx.showToast({
                                title: "购买成功！",
                                icon: "success",
                                success: function() {
                                    common.request({
                                        endpoint: "v1/Supermarket/order/sync-notify",
                                        method: "post",
                                        data: {
                                            order_sn: order_no
                                        },
                                        success: res => {
                                            setTimeout(function() {
                                                wx.reLaunch({
                                                    url: "/localLifePackage/pages/order/order"
                                                });
                                            }, 500);
                                        },
                                        fail(err) {
                                            wx.showModal({
                                                title: "提示",
                                                content: err.message
                                            });
                                        }
                                    });
                                }
                            });
                        }
                    });
                },
                fail: function(res) {
                    wx.reLaunch({
                        url: "/localLifePackage/pages/order/order",
                        success: function(e) {
                            let page = getCurrentPages().pop();
                            if (page == undefined || page == null) return;
                            page.onLoad();
                        }
                    });
                }
            });
        } else if (payment_channel == 1) {//余额支付
        }
    },
    //设置支付方式
    setPayWay: function(detail) {
        var _this = this;
        var payWayList1 = _this.data.payWayList1;
        var payWayList = [];
        payWayList1.forEach(item => {
            if (detail.balance.balance_display == 1 && item.payWayName == "余额" || item.payWayName == "微信支付") {
                payWayList.push(item);
            }
        });
        var balanceNumTip = "";
        var specFundNumTip = "";
        var payment_channel = 2;
        //支付方式
                payWayList.forEach(item => {
            if (item.payWayName == "余额" && parseFloat(detail.balance.my_balance) >= parseFloat(detail.total_amount)) {
                balanceNumTip = "（余额：￥" + detail.balance.my_balance + "）";
                payment_channel = 1;
            }
            if (item.payWayName == "余额" && parseFloat(detail.balance.my_balance) < parseFloat(detail.total_amount)) {
                balanceNumTip = "（余额不足：￥" + detail.balance.my_balance + "）";
                item.isDisabled = true;
            }
        });
        _this.setData({
            payWayList: payWayList,
            //支付方式
            payment_channel: payment_channel,
            balanceNumTip: balanceNumTip,
            //余额提示
            specFundNumTip: specFundNumTip
        });
    },
    recordValue: function(e) {
        this.setData({
            remark: e.detail.value
        });
    },
    choseMethod: function(e) {
        let that = this;
        var chose_delivery_channel = e.currentTarget.dataset.id;
        var chose_delivery_channel_name = e.currentTarget.dataset.name;
        that.setData({
            chose_delivery_channel: chose_delivery_channel,
            chose_delivery_channel_name: chose_delivery_channel_name
        });
        that.getOrder();
    },
    close_balance_confirm() {
        this.setData({
            balance_confirm: 0
        });
    },
    confirm_balance: function() {
        this.confirm_order();
    },
    choose_label: function(e) {
        var that = this;
        var id = e.currentTarget.dataset.id;
        that.setData({
            discount_label: id
        });
    },
    //选择红包
    choose_discount: function(e) {
        var id = e.currentTarget.dataset.id;
        if (this.data.voucher_id == id) {
            this.setData({
                voucher_id: null,
                voucher_use: false
            });
        } else {
            this.setData({
                voucher_id: id,
                voucher_use: true
            });
        }
        this.getOrder();
    },
    show_discount: function() {
        var that = this;
        that.setData({
            discount_alert: 1
        });
    },
    confirm_discount: function() {
        this.setData({
            discount_alert: 0
        });
    }
});